<?php
class Login extends Controller {

    function __construct()
    {
        parent::Controller();
        $this->load->model('Users_model');
    }

    function index()
    {
        $this->load->helper('form');
        $this->load->view('open_html');
        $this->load->view('login_view');
        $this->load->view('close_html');
    }

    function process()
    {
        $this->load->helper('url');
        $mail = $this->input->post('mail');
        $nombre = $this->input->post('nombre');
        $rut =$this->input->post('rut');
        $dv = $this->input->post('dv');
        if (!is_numeric($rut))
            {
                redirect ('/login');
                return;
            }
        $rut = $rut.$dv;
        if (!$this->valida_rut($rut))
            {
                redirect ('/login');
                return;
            }

        if (strlen($nombre)<5)
            {
                redirect ('/login');
                return;
            }
        if (strlen($mail)<6)
            {
                redirect ('/login');
                return;
            }

        $this->load->model('Users_model');
        $this->Users_model->register($nombre,$rut,$mail);
        redirect('/main');
     }

     function valida_rut($r)
{
	$r=strtoupper(ereg_replace('\.|,|-','',$r));
	$sub_rut=substr($r,0,strlen($r)-1);
	$sub_dv=substr($r,-1);
	$x=2;
	$s=0;
	for ( $i=strlen($sub_rut)-1;$i>=0;$i-- )
	{
		if ( $x >7 )
		{
			$x=2;
		}
		$s += $sub_rut[$i]*$x;
		$x++;
	}
	$dv=11-($s%11);
	if ( $dv==10 )
	{
		$dv='K';
	}
	if ( $dv==11 )
	{
		$dv='0';
	}
	if ( $dv==$sub_dv )
	{
		return true;
	}
	else
	{
		return false;
	}
}



}
?>
